<template>
  <el-dialog
    v-model="dialogVisible"
    draggable
    :z-index="500"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    title="文章管理"
    width="980px"
    center
    top="5vh"
  >
    <el-form ref="formRef" :model="formValue" :rules="rules" label-width="80px" status-icon>
      <el-row :gutter="20">
        <el-col :span="17">
          <el-form-item label="标题" prop="title" label-width="50px">
            <el-input v-model="formValue.title" placeholder="标题"></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="ontop" label-width="50px">
            <editor v-model="formValue.content"></editor>
          </el-form-item>
        </el-col>

        <el-col :span="7">
          <el-form-item label="所属栏目" prop="category">
            <el-select-v2
              style="width: 100%"
              v-model="formValue.category"
              :options="categoryList"
              placeholder="所属栏目"
            ></el-select-v2>
          </el-form-item>

          <el-form-item label="封面图">
            <el-upload
              ref="uploadRef"
              class="avatar-uploader"
              action="api/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :auto-upload="false"
              :on-change="uploadChange"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item label="关键词" prop="keyword">
            <el-input v-model="formValue.keyword" placeholder="关键词"></el-input>
          </el-form-item>

          <el-form-item label="是否置顶" prop="istop">
            <el-radio-group v-model="formValue.istop" class="ml-4" style="margin-top: -4px">
              <el-radio :label="1" size="large">是</el-radio>
              <el-radio :label="0" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="发布时间" prop="issueTime">
            <el-date-picker
              style="width: 100%"
              v-model="formValue.issueTime"
              type="datetime"
              placeholder="发布时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="来源" prop="source">
            <el-input v-model="formValue.source" placeholder="来源"></el-input>
          </el-form-item>

          <el-form-item label="原文链接" prop="link">
            <el-input
              v-model="formValue.link"
              type="textarea"
              rows="2"
              placeholder="例：https://www.baidu.com/"
            ></el-input>
          </el-form-item>

          <el-form-item label="审核状态" prop="auditState" position="left" v-has="'article:audit'">
            <el-radio-group v-model="formValue.auditState" class="ml-4" style="margin-top: -4px">
              <el-radio :label="1" size="large">通过</el-radio>
              <el-radio :label="0" size="large">驳回</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核描述" prop="auditDescribe" v-has="'article:audit'">
            <el-input
              v-model="formValue.auditDescribe"
              type="textarea"
              rows="1"
              placeholder="审核描述"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <div style="text-align: center" v-has="['article:add', 'article:edit']">
        <el-button type="warning" auto-insert-space @click="yuLan">预览</el-button>
        <el-button type="success" auto-insert-space @click="submitTwo(formRef)">保存</el-button>
        <el-button
          type="primary"
          auto-insert-space
          @click="submit(formRef)"
          v-has="'article:audit'"
        >
          {{ formValue.auditState == 0 ? '提交' : '发布' }}
        </el-button>
        <el-button @click="reset" auto-insert-space>重置</el-button>
      </div>
    </el-form>
  </el-dialog>

  <UploadFileVueCropper ref="uploadfilevuecropper" @setPicture="setPicture"></UploadFileVueCropper>

  <ArticlePreview ref="articlepreview"></ArticlePreview>
</template>

<script lang="ts" setup>
import editor from '@/components/tools/Editor.vue'
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules, ElMessage, ElMessageBox, UploadInstance } from 'element-plus'
import { getListByParentCode } from '@/apis/sysdict.js'
import {
  articlegetById,
  articleSave,
  articleUpdateById,
  articleZanCunById
} from '@/apis/article.js'
import { useAuthStore } from '@/stores/user'

import ArticlePreview from '@/views/Article/ArticlePreview.vue'

const store = useAuthStore()

const formRef = ref()

const imageUrl = ref()
const fileList = ref()

let formValue = ref({
  no: '',
  title: '',
  content: '',
  category: null,
  picture: '',
  keyword: '',
  istop: 0,
  issueTime: '',
  source: '',
  link: '',
  auditState: null,
  auditDescribe: '',
  account: store.user.userInfo.userid
})
const uploadRef = ref<UploadInstance>()

const validateAuditDescribe = (rule: any, value: any, callback: any) => {
  if (formValue.value.auditState == 0) {
    if (value === '') {
      callback(new Error('请填写审核描述'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

const validateLink = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback()
  } else {
    // const reg = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+$/
    const reg =
      /^(http|https):\/\/[\w\-_\u4E00-\u9FA5:/]+(\.[\w\-_\u4E00-\u9FA5]+)+([\u4E00-\u9FA5\w\-.,@?^=%&:/~+#]*[\u4E00-\u9FA5\w\-@?^=%&/~+#])?$/
    // const reg =
    //   /^(?:(http|https|ftp):\/\/)?((?:[a-zA-Z0-9\u4e00-\u9fa5]+\.)+[a-zA-Z0-9\u4e00-\u9fa5]+)((?:\/[^/?#]*)+)?(\?[^#]+)?(#.+)?$/

    if (!reg.test(value)) {
      callback('输入的原文链接有误')
    } else {
      callback()
    }
  }
}

const validateAuditState = (rule: any, value: any, callback: any) => {
  callback()
}

let rules = ref<FormRules>({
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  category: [{ required: true, message: '请选择所属栏目', trigger: 'change' }],
  order: [{ required: true, type: 'number', message: '排序必须为数字值', trigger: 'blur' }],
  auditState: [{ required: true, validator: validateAuditState }],
  // auditDescribe: [{ validator: validateAuditDescribe }],
  issueTime: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
  link: [{ validator: validateLink }]
})

let dialogVisible = ref(false)

const options = Array.from({ length: 10 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`
}))

let originValue = {}

function open(no) {
  getCategoryList('ArticleCategroy')

  if (no != null) {
    articlegetById({ no })
      .then(function (response) {
        formValue.value = response
        imageUrl.value = response.picture
        originValue = JSON.parse(JSON.stringify(response))
      })
      .catch(function (error) {
        console.log(error)
      })
  } else {
    let yy = new Date().getFullYear()

    let mount = new Date().getMonth() + 1

    let mm = mount < 10 ? '0' + mount : mount
    let dd = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()
    let hh = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours()
    let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
    let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()

    let time = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss

    let v = {
      no: '',
      title: '',
      content: '',
      category: null,
      picture: '',
      keyword: '',
      istop: 0,
      issueTime: time,
      source: '',
      link: '',
      auditState: null,
      auditDescribe: '',
      account: store.user.userInfo.userid
    }

    imageUrl.value = null

    formValue.value = v

    originValue = JSON.parse(JSON.stringify(v))
  }

  dialogVisible.value = true

  reset()
}

const submit = async (formEl: FormInstance | undefined) => {
  rules.value = {
    title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
    category: [{ required: true, message: '请选择所属栏目', trigger: 'change' }],
    order: [{ required: true, type: 'number', message: '排序必须为数字值', trigger: 'blur' }],
    auditState: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
    auditDescribe: [{ validator: validateAuditDescribe }],
    issueTime: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
    link: [{ validator: validateLink }]
  }

  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      baoCun()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const submitTwo = async (formEl: FormInstance | undefined) => {
  rules.value = {
    title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
    category: [{ required: true, message: '请选择所属栏目', trigger: 'change' }],
    order: [{ required: true, type: 'number', message: '排序必须为数字值', trigger: 'blur' }],
    auditState: [{ required: true, validator: validateAuditState }],
    // auditState: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
    // auditDescribe: [{ validator: validateAuditDescribe }],
    issueTime: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
    link: [{ validator: validateLink }]
  }

  formRef.value?.clearValidate(['auditState', 'auditDescribe'])

  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      zanCun()
    } else {
      console.log('error submit!', fields)
    }
  })
}

function zanCun() {
  // uploadRef.value!.submit()

  ElMessageBox.confirm('确定要保存吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      articleZanCunById(formValue.value)
        .then(function (response) {
          if (response != null) {
            formValue.value = response
            imageUrl.value = response.picture
            originValue = JSON.parse(JSON.stringify(response))
            ElMessage({
              type: 'success',
              message: '保存成功'
            })
            emit('getPage')
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消保存'
      })
    })
}

const emit = defineEmits(['getPage'])

function baoCun() {
  // uploadRef.value!.submit()

  ElMessageBox.confirm(
    '确定要' + (formValue.value.auditState == 0 ? '提交' : '发布') + '吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      if (formValue.value.no == '') {
        articleSave(formValue.value)
          .then(function (response) {
            if (response) {
              ElMessage({
                type: 'success',
                message: (formValue.value.auditState == 0 ? '提交' : '发布') + '成功'
              })
              dialogVisible.value = false
              emit('getPage')
            }
          })
          .catch(function (error) {
            console.log(error)
          })
      } else if (formValue.value.no != null) {
        articleUpdateById(formValue.value)
          .then(function (response) {
            if (response) {
              ElMessage({
                type: 'success',
                message: (formValue.value.auditState == 0 ? '提交' : '发布') + '成功'
              })
              dialogVisible.value = false
              emit('getPage')
            }
          })
          .catch(function (error) {
            console.log(error)
          })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消' + (formValue.value.auditState == 0 ? '提交' : '发布')
      })
    })
}

function reset() {
  if (!formRef) return
  formRef.value.resetFields()

  formValue.value = JSON.parse(JSON.stringify(originValue))
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  formValue.value.picture = response
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片必须是JPG、PNG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

let uploadfilevuecropper = ref()

function uploadChange(file) {
  // imageUrl.value = URL.createObjectURL(file.raw)
  uploadfilevuecropper.value.open(file)
}

let categoryList = ref([])

function getCategoryList(category) {
  categoryList.value = []

  getListByParentCode(category)
    .then((response) => {
      response.forEach((element) => {
        categoryList.value.push({ value: element.code, label: element.name })
      })
    })
    .catch((error) => {
      console.log(error)
    })
}

function setPicture(picture) {
  formValue.value.picture = picture
  imageUrl.value = picture
}
let articlepreview = ref()
function yuLan() {
  articlepreview.value.open(formValue.value)
}

defineExpose({ open })

onMounted(() => {
  // getCategoryList('ArticleCategroy')
})
</script>

<style scoped>
:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}
:deep(.avatar-uploader .avatar) {
  width: 176px;
  height: 99px;
  display: block;
}
:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 176px;
  height: 99px;
  text-align: center;
}

:deep(.edui_fixedlayer) {
  z-index: 3000 !important;
}
</style>
